package com.bw.home.vm

import com.blankj.utilcode.util.GsonUtils
import com.bw.common.entity.CommendEntity
import com.bw.common.vm.BaseViewModel
import com.bw.home.intent.HomeViewIntent
import com.bw.home.intent.VideoViewIntent
import com.bw.home.repo.HomeRepository
import com.bw.home.state.HomeUiState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import javax.inject.Inject
/**
*  stateFlow 和ShareFlow的区别
 *  1是否需要设置默认值 StateFlow 必须设置，SharedFlow不需要
 *  2 是否接收相同的值 ，StateFlow 不能，ShareFlow可以
 *  3 是否存在缓存 StateFlow没有缓存，SharedFlow有缓存
 *  4 是否可以多次订阅接收数据：1.StateFlow不能，ShareFlow可以
* */
@HiltViewModel
class HomeViewModel @Inject constructor(private val repository: HomeRepository) :
    BaseViewModel<HomeViewIntent>() {
    //私有的防止外部修改StateFlow
    //private val _uiStateFlow = MutableStateFlow<HomeUiState>(HomeUiState.LoadEmpty)
    private val _uiSharedFlow = MutableSharedFlow<HomeUiState>()
    //对外暴露一个StateFLow用于收集数据变化
    //val uiStateFlow: SharedFlow<HomeUiState> = _uiStateFlow.asSharedFlow()
    val uiSharedFlow: SharedFlow<HomeUiState> = _uiSharedFlow.asSharedFlow()
    /**
     *  分发View层的意图
     **/
    override fun dispatchIntent(intent: HomeViewIntent) {
        when (intent) {
            is HomeViewIntent.LoadVideType -> loadSimpleType()
            is HomeViewIntent.LoadRecommendSimpleVideoList -> loadRecommendSimpleVideoList(
                intent.pageIndex,
                intent.pageSize
            )

            is HomeViewIntent.LoadSimpleVideoList -> loadSimpleVideoListByChannelId(
                intent.channelId,
                intent.pageIndex,
                intent.pageSize
            )

            is HomeViewIntent.LoadVideoCommentList -> loadVideoCommentList(
                intent.dataType,
                intent.itemId
            )

            is HomeViewIntent.PublishVideoComment -> publishVideoComment(intent.entity)
            is VideoViewIntent.LoadVideoDetail -> TODO()
        }
    }

    /**
     *      * 加载视频分类
     *           */
    private fun loadSimpleType() {
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            repository.getSimpleType().collect { list ->
                if (list.isNotEmpty()) {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadSimpleTypeSuccess(list)
                    )
                } else {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadSimpleTypeFail("没有获取到视频分类!")
                    )
                }
            }
        }
    }


    /**
     *      * 获取推荐视频列表
     *           */
    private fun loadRecommendSimpleVideoList(page: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            repository.getRecommendSimpleVideoList(page, pageSize).collect { list ->
                if (list.isNotEmpty()) {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadSimpleVideoSuccess(list)
                    )
                } else {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadSimpleVideoFail("没有获取到推荐视频!")
                    )
                }
            }
        }
    }

    /**
     *      * 获取分类下视频列表
     *           */
    private fun loadSimpleVideoListByChannelId(channelId: String, pageIndex: Int, pageSize: Int) {
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            repository.getSimpleVideoList(channelId, pageIndex, pageSize).collect { list ->
                if (list.isNotEmpty()) {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadSimpleVideoSuccess(list)
                    )
                } else {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadSimpleVideoFail("没有获取到该分类下的视频!")
                    )
                }
            }
        }

    }

    /**
     *      * 获取视频评论列表
     *           */
    private fun loadVideoCommentList(dataType: Int, itemId: String) {
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            repository.getVideoCommends(itemId, dataType).collect { list ->
                if (list.isNotEmpty()) {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadVideoCommentSuccess(list)
                    )
                } else {
                    _uiSharedFlow.emit(
                        HomeUiState.LoadVideoCommentFail("没有获取到该视频的评论!")
                    )
                }
            }
        }

    }

    /**
     *      * 发布视频评论
     *           */
    private fun publishVideoComment(commentEntity: CommendEntity) {
        mViewModelScope.launch(mDispatcher) {
            //发送请求并收集数据
            val requestBody: RequestBody = GsonUtils.toJson(commentEntity)
                .toRequestBody("application/json;charset=utf-8".toMediaTypeOrNull())
            repository.publishVideoComment(requestBody).collect { list ->
                if (list.isNotEmpty()) {
                    _uiSharedFlow.emit(
                        HomeUiState.PublishVideoCommentSuccess(list)
                    )
                } else {
                    _uiSharedFlow.emit(
                        HomeUiState.PublishVideoCommentFail("发布评论失败!")
                    )
                }
            }
        }

    }
}
